/*
 * Project: Set Sample
 * Copyright (C) 2013 alf.labs gmail com,
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.alflabs.setsample.presenter;

import android.os.Bundle;
import android.util.Log;
import com.alflabs.annotations.NonNull;
import com.alflabs.annotations.Null;
import com.alflabs.serial.SerialReader;
import com.alflabs.serial.SerialWriter;
import com.alflabs.setsample.core.GlobalContext;

public class SetPresenter extends SetPresenterImpl {

    private final static String TAG = SetPresenter.class.getSimpleName();

    public SetPresenter(@Null IAbstractView view) {
        super(view, GlobalContext.getInstance().getModel());
    }

    /**
     * Persist model's data + presenter (UI state) data to the bundle.
     */
    public void saveState(@NonNull Bundle bundle) {
        SerialWriter w = toSerial();
        int[] a = w.encodeAsArray();
        bundle.putIntArray("presenter+model", a);
    }

    /**
     * Restore bundle if its model seed is different or counter is newer.
     */
    public void restoreState(@NonNull Bundle bundle) {

        int[] a = bundle.getIntArray("presenter+model");
        if (a == null) return;

        try {
            SerialReader sr = new SerialReader(a);
            fromSerial(sr);
        } catch (Exception e) {
            Log.e(TAG, "Presenter fromSerial error: ", e);
        }
    }
}
